﻿package com.pandemicode.framework.smtp.mailer {
	import flash.utils.ByteArray;
	import com.pandemicode.framework.smtp.collections.EmailAddressCollection;
	import com.pandemicode.framework.smtp.collections.EmailAttachmentCollection;
	import flash.utils.getTimer;
	import com.pandemicode.framework.smtp.mailer.parts.HTML;
	import com.pandemicode.framework.smtp.mailer.parts.MultiPartAlternative;
	import com.pandemicode.framework.smtp.mailer.parts.MultiPartRelated;
	import com.pandemicode.framework.smtp.mailer.parts.Text;
	
	/**
	* @author Mike Lawrence
	*/
	public class EmailMessage {
		private var _from:EmailAddress;
		private var _to:EmailAddressCollection;
		private var _subject:String;
		private var _message:String;
		private var _isHTML:Boolean;
		private var _attachments:EmailAttachmentCollection;
		private var _host:String;
		
		public function get content():String {
			var mr:MultiPartRelated = new MultiPartRelated("multipart/alternative", Mailer.NEWLINE + "This is a multi-part message in MIME format." + Mailer.NEWLINE + Mailer.NEWLINE);
			var ma:MultiPartAlternative = new MultiPartAlternative();
			
			var c:String = "HELO " + this._host + Mailer.NEWLINE;
			c += "MAIL FROM: " + this._from.formattedWithoutName + Mailer.NEWLINE;
			
			for each(var toAddress:EmailAddress in this._to)
				c += "RCPT TO: " + toAddress.formattedWithoutName + Mailer.NEWLINE;
				
			c += "DATA" + Mailer.NEWLINE;

			c += "From: " + this._from.toString() + Mailer.NEWLINE;
			c += "To: " + this._to.toString() + Mailer.NEWLINE;
			c += "Date: " + new Date().toString() + Mailer.NEWLINE;
			
			if(this._subject != null)
				c += "Subject: " + this._subject + Mailer.NEWLINE;
				
			c += "Mime-Version: 1.0" + Mailer.NEWLINE;
			
			c += mr.toString();
			
			c += mr.boundary.valueDashed;
			c += ma.toString();

			// The message
			if (this._message != null && this._message.length > 0) {
				c += ma.boundary.valueDashed;
				if (this._isHTML) // The html message
					c += new HTML(this._message).toString();
				else // The text message
					c += new Text(this._message).toString();
				c += Mailer.NEWLINE;
			}
			
			// The attachments
			c += this._attachments.format(mr.boundary);
			
			c += "." + Mailer.NEWLINE;
			return c;
		}
		
		public function EmailMessage(host:String, to:EmailAddressCollection, from:EmailAddress, subject:String = null, message:String = null, isHTML:Boolean = true, attachments:EmailAttachmentCollection = null) {
			this._host = host;
			this._to = to;
			this._from = from;
			this._subject = subject;
			this._message = message;
			this._isHTML = isHTML;
			this._attachments = attachments;
		}
		
		public function toString():String {
			return this.content;
		}
	}
}
